package xj.graph2d.app.prop;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JFrame;

import xj.graph2d.table.FeatureTableEntry;
import xj.model.uml.NamedElement;
import xj.model.uml.Operation;
import xj.model.uml.Parameter;

public class ParameterField extends FeatureListField {

  public ParameterField() {
    super();
  }

  public ParameterField(JFrame owner, String displayName) {
    super(owner, displayName, "Parameters", false, false);
  }

  @Override
  public void updateEditorValue() {
    java.util.List<FeatureTableEntry> entries = featurePanel.getEntries();
    if (entries != null) {
      entries.clear();
    } else {
      entries = new ArrayList<FeatureTableEntry>();
    }
    if (model instanceof Operation) {
      Operation op = (Operation) model;
      List<Parameter> parameters = op.getParameters();
      if (parameters != null) {
	Iterator<Parameter> iter = parameters.iterator();
	while (iter.hasNext()) {
	  Parameter param = iter.next();
	  entries.add(new UMLParameterEntry(param));
	}
      }
    }
    if (entries.isEmpty()) {
      entries.add(makeNewEntry());
    }
    featurePanel.setEntries(entries);

    if (featureDialog != null) {
      String name = null;
      String element = null;
      if (model instanceof NamedElement) {
	name = ((NamedElement) model).getName();
      }
      if (name == null || name.length() == 0) {
	name = "<unnamed>";
      }
      element = "[" + model.getElementName() + "]";
      featurePanel.setTableTitle("Parameters of", name, element);
    }
  }

  @Override
  public void updateModelValue() {
    java.util.List<FeatureTableEntry> entries = featurePanel.getEntries();
    if (model instanceof Operation) {
      Operation op = (Operation) model;
      op.removeAllParameters();
      if (entries != null) {
	Iterator<FeatureTableEntry> iter = entries.iterator();
	while (iter.hasNext()) {
	  FeatureTableEntry fe = iter.next();
	  if (fe instanceof UMLParameterEntry) {
	    UMLParameterEntry entry = (UMLParameterEntry) fe;
	    Parameter param = entry.getParameter();
	    String name = param.getName();
	    if (name != null) {
	      name = name.trim();
	      if (name.length() > 0) {
		op.addParameter(param);
	      }
	    }
	  }
	}
      }
    }
  }

  static FeatureTableEntry proto = new UMLParameterEntry(null);

  @Override
  public FeatureTableEntry getPrototype() {
    return proto;
  }

  @Override
  public FeatureTableEntry makeNewEntry() {
    Parameter param = new Parameter();
    return new UMLParameterEntry(param);
  }

}
